﻿using System;
using Enyim.Caching;
using Ayatta.Contract;
using Web.Pay.Models;
using System.Web.Mvc;
using Web.Core.Security;
using Ayatta.Contract.Domain;

namespace Web.Pay.Controllers
{
    public class PlatformController : BaseController
    {
        public PlatformController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {

        }

        public void Index()
        {

        }

        /// <summary>
        /// 第三方支付平台异步通知
        /// </summary>
        /// <param name="param">第三方支付平台</param>
        /// <returns></returns>
        public ActionResult Notify(Platform param)
        {
            var pay = GetOnlinePay(param);
            var result = pay.NotifyHandler(param == Platform.AliPay ? Request.Form : Request.QueryString);
            if (param == Platform.ChinaPay)
            {
                return new HttpStatusCodeResult(result.Status ? 200 : 500);
            }
            return Content(result.Data.Token);
        }

        /// <summary>
        /// 第三方支付平台支付完成后跳回
        /// </summary>
        /// <param name="param">第三方支付平台</param>
        /// <returns></returns>
        public ActionResult Callback(Platform param)
        {
            var pay = GetOnlinePay(param);
            var result = pay.NotifyHandler(Request.QueryString);
            return Redirect("/platform/result/" + result.Data.No);//跳转到结果页面统一处理
        }

        /// <summary>
        /// 支付结果
        /// </summary>
        /// <param name="param">系统支付订单号</param>
        /// <returns></returns>
        public ActionResult Result(string param)
        {
            var model = new PlatformControllerModel.Result();
            var identity = User.Identity.Identity();
            if (Request.IsAuthenticated)
            {
                var account = Account.Value.AccountGet(identity.Id);
                var payment = Account.Value.AccountPaymentGet(param);

                model.Account = account;
                model.Payment = payment;

                if (payment.Category == PaymentCategory.Recharge)
                {
                    var recharge = Account.Value.AccountRechargeGet(payment.ForeignKey);
                    model.Recharge = recharge;
                }

            }
            return View(model);
        }
    }
}
